<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/20
 * Time: 14:52
 */

namespace Game\Services;
use Game\Lib\CodeConst;
use Game\Lib\Game;
use Game\Lib\OPT_CONST;
use Game\Library\Logger;
use Game\Library\Socket;
use Game\Traits\Singleton;
use GatewayWorker\Lib\Gateway;
class BaseOperation
{
    use Singleton;


    /**
     * 组装返回值
     * @param $result
     * @param string $operation
     * @return mixed
     */
    public function formartReturn($result,$operation='')
    {
        //判断返回结果
        if(is_array($result)) {
            $resultArray = $result;
        } else {
            $resultArray = array('result'=>$result,'operation'=>$operation,'data'=>array(),'result_message'=>"");
        }
        return Tools::getInstance()->_JSON($resultArray);		//编译为JSON格式,返回结果
    }

    protected function writeLog($message, $level = "INFO"){
        Logger::getInstance()->log($message,$level);
    }

    

    

    /**
     * 推给定时器服务器
     * @param string $msg_array
     * @return bool
     */
    public function sendToTimerServer($msg_array = "")
    {
        $message = Tools::getInstance()->_JSON($msg_array);
        $socket_name = "Timer";
        Socket::getInstance($socket_name)->sendMessageToSocket($socket_name,$message);
        return true;
    }
    /**
     * 删除定时器
     * @param $room_id
     */
    protected function deleteRoomTimer($room_id){
        $timer_id = GameData::getInstance()->queryTimerId($room_id);
        if($timer_id > 0){
            $arr = array(
                'operation' => "DeleteTimer",
                'room_id'   => $room_id,
                'data' => array(
                    'timer_id' => $timer_id
                )
            );
            $this->sendToTimerServer($arr);
        }
        GameData::getInstance()->updateTimer($room_id, -1);
    }

    /**
     * 设置 清理房间 定时器
     * @param $room_id
     */
    protected function setupClearRoomPassiveTimer($room_id){
        $this->writeLog("[$room_id] 设置自动清扫房间定时器");
        $arr = array(
            'operation' => "BuildTimer",
            'room_id'   => $room_id,
            'data' => array(
                'limit_time' => Game::LimitTime_ClearRoom,
                'callback_array' =>  array(
                    'operation' => "ClearRoomPassive",
                    'room_id' => $room_id,
                    'data' => array()
                )
            )
        );
        $this->sendToTimerServer($arr);
    }

    protected function logMessage($level, $content){
        Logger::getInstance()->log($content, $level);
    }

    protected function _missingPrameterArr($operation, $prameter){
        return array('result'=>CodeConst::Error_MissingParameter,'operation'=>$operation,'data'=>array("missing_parameter"=>$prameter),'result_message'=>"缺少参数");
    }

}